//
//  NetDataPath.m
//  CargocnRun
//
//  Created by mac on 2017/3/24.
//  Copyright © 2017年 mac. All rights reserved.
//

#import "NetDataPath.h"
#import "NSObject+AutoDescription.h"
#import "BaseRequestModel.h"
static NetDataPath *_sharedInstance;

@implementation NetDataPath



{
    BaseRequestModel *_baseRequestModel;
    AFHTTPSessionManager *_manager;
}

+ (NetDataPath *)sharedInstance
{
    @synchronized(self){
        if(_sharedInstance == nil) {
            _sharedInstance = [[NetDataPath alloc] init];
            
        }
        return _sharedInstance;
    }
}
- (id)init {
    self = [super init];
    if (self) {
        _manager = [AFHTTPSessionManager manager];
        _baseRequestModel = [[BaseRequestModel alloc]init];
        
    }
    return self;
}
-(void)requestDataWith:(id)sender WithModel:(BaseRequestModel *)requestModel complition:(void(^)(id result,id requestError)) completion
{
    self.requestController = sender;
//    ILog(@"这里是请求的viewController%@",self.requestController);
    [self addCookie];
    BaseRequestModel *bse = [[BaseRequestModel alloc] init];
    NSMutableDictionary *requestDic = (NSMutableDictionary *)[requestModel dictionaryFromAttributes];
    NSMutableDictionary *baseRequestModelDic = (NSMutableDictionary *)[bse dictionaryFromAttributes];
    //[baseRequestModelDic removeObjectForKey:@"transCode"];
    //[baseRequestModelDic removeObjectForKey:@"sessionid"];
//    ILog(@"这里是requestDic%@",requestDic);
    NSEnumerator * enumeratorKey = [baseRequestModelDic keyEnumerator];
    //定义一个不确定类型的对象
    NSString * key;
    //遍历输出
    while(key = [enumeratorKey nextObject])
    {
        [requestDic removeObjectForKey:key];
    }
    
    
    
    
    
    NSString *url = [NSString new];
    
    //添加网络请求的app类型
    [requestDic setObject:@"ios" forKey:@"fromApp"];
    [requestDic setObject:@"15" forKey:@"appType"];
    [requestDic setObject:[ValueUtils clientVersion] forKey:@"appVersion"];
    
    if ([requestModel.httpUrl length]>0)
    {
        url = requestModel.httpUrl;
    }
    else
    {
        url = @"http://test.cargocn.cn/cargocn/";
    }
    url = [url stringByAppendingString:requestModel.methodName];
    MITLog(@"\n%@\n%@\n%@",sender,url,requestDic);
    
    _manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    [_manager POST:url parameters:requestDic progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
        
        if ([requestModel.transCode isEqualToString:@"DriverLogin"])
        {
            NSHTTPCookieStorage *sharedHTTPCookieStorage = [NSHTTPCookieStorage sharedHTTPCookieStorage];
            NSDictionary* dic = ((NSHTTPURLResponse*)task.response).allHeaderFields;

            NSString* cookie = [dic valueForKey:@"Set-Cookie"];

            if(!IsNilString(cookie))
            {
                [[LocalDataManager sharedLocalDataManager] setObjectWithNSUserDefaults:cookie forUsername:LocalData_Cookie_Key];
            }

        }
        
        
        completion(dict,nil);

    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        completion(task,error);
    }];
}
-(void)requestUpdateImage:(id)sender WithModel:(BaseRequestModel *)requestModel complition:(void(^)(id result,id requestError)) completion
{
    [self addCookie];
    self.requestController = sender;
    
    BaseRequestModel *bse = [[BaseRequestModel alloc] init];
    NSMutableDictionary *requestDic = (NSMutableDictionary *)[requestModel dictionaryFromAttributes];
    NSMutableDictionary *baseRequestModelDic = (NSMutableDictionary *)[bse dictionaryFromAttributes];
    //[baseRequestModelDic removeObjectForKey:@"transCode"];
    //[baseRequestModelDic removeObjectForKey:@"sessionid"];
    ILog(@"这里是requestDic%@",requestDic);
    NSEnumerator * enumeratorKey = [baseRequestModelDic keyEnumerator];
    //定义一个不确定类型的对象
    NSString * key;
    //遍历输出
    while(key = [enumeratorKey nextObject])
    {
        [requestDic removeObjectForKey:key];
    }
    
    
    
    
    
    NSString *url = [NSString new];
    
    //添加网络请求的app类型
    [requestDic setObject:@"ios" forKey:@"fromApp"];
    [requestDic setObject:@"15" forKey:@"appType"];
    [requestDic setObject:[ValueUtils clientVersion] forKey:@"appVersion"];
    
    if ([requestModel.httpUrl length]>0)
    {
        url = requestModel.httpUrl;
    }
    else
    {
        url = @"http://test.cargocn.cn/cargocn/";
    }
    
    url = [url stringByAppendingString:requestModel.methodName];
    
    
    NSMutableDictionary* dic = [NSMutableDictionary dictionaryWithCapacity:3];
    NSArray* array = [requestDic allKeys];
    for(int i = 0; i < [array count]; ++i)
    {
        id val = [requestDic objectForKey:[array objectAtIndex:i]];
        if(![val isKindOfClass:[NSData class]])
        {
            [dic setValue:val forKey:[array objectAtIndex:i]];
        }
    }
    
    MITLog(@"%@\n%@",url,dic);
    
//    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    _manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    _manager.responseSerializer.acceptableContentTypes =[NSSet setWithObjects:@"application/json", @"text/html", @"text/json", @"text/javascript",@"text/plain", nil];
        _manager.responseSerializer.acceptableContentTypes =[NSSet setWithObjects:@"application/json", @"text/html", @"text/json", @"text/javascript",@"text/plain", nil];
        [_manager POST:url parameters:dic constructingBodyWithBlock:^(id<AFMultipartFormData> formData)
         {
             
             NSArray* arr = [requestDic allKeys];
             for(int i = 0; i < [arr count]; ++i)
             {
                 if([arr[i] isEqualToString:@"feature1"]
                    ||
                    [arr[i] isEqualToString:@"feature2"])
                 {
                     [formData appendPartWithFormData:[requestDic objectForKey:arr[i]] name:arr[i]];
                 }
                 else if([[requestDic objectForKey:[arr objectAtIndex:i]] isKindOfClass:[NSData class]])
                 {
                     [formData appendPartWithFileData:[requestDic objectForKey:arr[i]] name:arr[i] fileName:@"image.jpeg" mimeType:@"image/jpeg"];
                 }
                 
             }
         }
             progress:^(NSProgress * _Nonnull uploadProgress) {
                 
             }success:^(NSURLSessionDataTask *task, id responseObject)
         {
             NSDictionary *  responseObject1 = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
             completion(responseObject1,nil);

         } failure:^(NSURLSessionDataTask *task, NSError *error)
         {
             completion(task,error);
         }];

}
- (void)addCookie
{
    NSString* cookie = [[LocalDataManager sharedLocalDataManager] getObjectWithNSUserDefaults:LocalData_Cookie_Key];
    
    if(!IsNilString(cookie))
    {
        _manager.requestSerializer.HTTPShouldHandleCookies = YES;
        [_manager.requestSerializer setValue:cookie forHTTPHeaderField:@"Cookie"];
    }
    else
    {
        _manager.requestSerializer.HTTPShouldHandleCookies = YES;
    }
}
@end
